package com.scpii.api.common.json.serializer;

import java.io.IOException;

import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.JsonProcessingException;
import org.codehaus.jackson.map.JsonSerializer;
import org.codehaus.jackson.map.SerializerProvider;

import com.scpii.api.common.Constants;
import com.scpii.api.domain.content.Body;

public class BodySerializer extends JsonSerializer<Body> {

	@Override
	public void serialize(Body value, JsonGenerator jgen,
			SerializerProvider provider) throws IOException,
			JsonProcessingException {
		jgen.writeStartObject();
		if (value.getTitle() != null) {
			jgen.writeStringField("title", value.getTitle());
		}
		if (value.getValue() != null) {
			if (Body.TYPE_IMAGE.equals(value.getType())
					&& !ResourceUrlSerializer.URL_REG_PATTERN.matcher(
							value.getValue()).matches()) {
				String relativeURL = value.getValue();
				if (!relativeURL.startsWith("/")){
					relativeURL = "/" + relativeURL;
				}
				value.setValue(Constants.RESOURCE_ROOT_URL
						+ relativeURL.trim());
			}
		} else {
			value.setValue(null);
		}
		if (value.getValue() != null) {
			jgen.writeStringField("value", value.getValue());
		}
		if (value.getType() != null) {
			jgen.writeStringField("type", value.getType());
		}
		jgen.writeEndObject();
	}
}
